package tmproject.hlhj.fhp.anwser.http

import android.util.JsonReader
import android.util.Log
import com.google.gson.Gson
import com.lzy.okgo.convert.Converter
import okhttp3.Response
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * Created by Never Fear   on 2018\8\6 0006.
Never More....
 */
public open class JsonConvert<T> : Converter<T> {
    private var type: Type? = null
    private lateinit var clazz: Class<T>

    fun JsonConvert() {}

    fun JsonConvert(type: Type) {
        this.type = type
    }

    fun JsonConvert(clazz: Class<T>){
        this.clazz = clazz
    }

    @Throws(Throwable::class)
    override fun convertResponse(response: Response): T? {
        val genericSuperclass = javaClass.genericSuperclass
        type = (genericSuperclass as ParameterizedType).actualTypeArguments[0]
        return pariseBean(type as Class<T>?, response)
    }

    @Throws(IOException::class, JSONException::class)
    private fun pariseBean(type: Class<T>?, response: Response): T? {
        if (type == null) return null
        Log.e("info", "开始")
        val body = response.body() ?: return null
        val reader = JsonReader(body.charStream())

        if (type == String::class.java) {
            Log.e("info", "开始1")
            return body.string() as T
        } else if (type == JSONObject::class.java) {
            Log.e("info", "开始2")
            return JSONObject(body.string()) as T
        } else if (type == JSONArray::class.java) {
            Log.e("info", "开始3")
            return JSONArray(body.string()) as T
        } else {
            Log.e("info", "开始4")
            val responceStr = body.string()
            val t = Gson().fromJson(responceStr, type)
            response.close()
            Log.e("info", "开始5")

            return t
        }
    }
}